#include "stdafx.h"

bool CSVOpener::Open()
{
	ifstream fin(openFileName);
	if (!fin)
		return false;

	int iRow = 1;
	char* strBuf = new char[5120];
	::ZeroMemory(strBuf, 5120);
	while (fin.getline(strBuf, 5120))
	{
		// this line in empty
		if (strlen(strBuf)==0)
		{
			iRow++;
			continue;
		}

		int iCol = 1;

		// ANSI -> Unicode
		const size_t newsize = 10240;
		wchar_t wcstring[newsize];
		long   lLen   =   MultiByteToWideChar(CP_ACP,0,strBuf,strlen(strBuf) + 1, wcstring , newsize);   
		wcstring[lLen] = TEXT('\0');

		
		// Analysis Column
		bool readComma = true;
		int i=0, iCellStart=-1, iCellEnd=-1;
		wstring wideString(wcstring);
		for (size_t i = 0; i < wideString.length(); i++)
		{
			if (wideString.c_str()[i] == TEXT('\"'))
			{
				readComma = ! readComma;
			}
			if (wideString.c_str()[i] == TEXT(',') || (int)i+1 == (int)wideString.length())
			{
				if (!readComma)
					continue;
				iCellEnd = i;
				if (wideString.c_str()[i] != TEXT(',') && (int)i+1 == (int)wideString.length())
					iCellEnd++;
				if (iCellEnd-iCellStart > 1)
				{
					wstring sub;
					if (iCellEnd - iCellStart >=3)
					{
						if (wideString.c_str()[iCellStart+1] == TEXT('\"') && wideString.c_str()[iCellEnd-1] == TEXT('\"'))
						{
							sub = wideString.substr(iCellStart+2, iCellEnd-iCellStart-3);
						}
						else
						{
							sub = wideString.substr(iCellStart+1, iCellEnd-iCellStart-1);
						}
					}
					else
					{
						sub = wideString.substr(iCellStart+1, iCellEnd-iCellStart-1);
					}
					// replace "" to "
					size_t pos = 0;
					pos = sub.find(TEXT("\"\""), pos);
					while(pos!= wstring::npos)
					{
						sub.replace(pos,2, TEXT("\""));
						pos ++;
						pos = sub.find(TEXT("\"\""), pos);
					}
					if (iCellEnd > iCellStart && sub.length()!=0)
					{
						MemState mem;
						pSheet->ModifyCellContent(iRow, iCol, sub.c_str(), mem);
					}
				}
				iCol++;
				iCellStart = i;
				readComma = true;
			}
		}
		iRow++;
	}
	fin.close();
	delete strBuf;
	return true;
}

bool CSVSaver::Save()
{
	wstring buf;
	pSheet->OutPutRegion(1,ROW_MAX,1,COL_MAX, buf,TEXT("\n"), TEXT(","), true);

	//Unicode -> ANSI
	size_t origsize = wcslen(buf.c_str()) + 1;
	size_t newsize = 2 * buf.length() + 2;
	char* nstring = new char[newsize];
	WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK, buf.c_str(), -1, nstring, newsize, NULL,NULL); 

	ofstream fout(saveFileName);
	if (!fout)
	{
		delete[] nstring;
		return false;
	}
	fout << nstring;
	fout.close();
	delete[] nstring;
	return true;
}